using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Caece.Libreria.FrontEnd;
using Caece.Libreria.DNS;
using System.Threading; 


namespace Caece.Libreria.Manager      
{   
    public partial class Form1 : Form
    {
		int _dnsPort;
		string _dnsIP;
		clsDNS _dns;
		int _dnsTimeOut;
		BerkeleyNode _server1;
		BerkeleyNode _server2;
		Thread _t1;
		Thread _t2;

		public Form1()
		{
			_dnsPort = Util.GetConfig<int>("DNS_Port");
			_dnsIP = Util.GetConfig<string>("DNS_IP");
			_dnsTimeOut = Util.GetConfig<int>("DNS_TimeOut");
			InitializeComponent();
			this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
		}

		void Form1_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (_t1 != null)
				_t1.Abort();

			if (_t2 != null)
				_t2.Abort();
		}

        private void button1_Click(object sender, EventArgs e)
        {
			_t1 = new Thread(IniciarNodo1);
			_t1.Start();			
        }

		private void button2_Click(object sender, EventArgs e)
		{
			_t2 = new Thread(IniciarNodo2);
			_t2.Start();	
		}

		private void button3_Click(object sender, EventArgs e)
		{
			_server1.RaiseEventClock();
		}

		private void button4_Click(object sender, EventArgs e)
		{
			_server2.RaiseEventClock();
		}

		private void button5_Click(object sender, EventArgs e)
		{
			_dns = new clsDNS(_dnsPort, _dnsTimeOut);
			_dns.Start();
		}

		private void button6_Click(object sender, EventArgs e)
		{
			if (_dns != null)
				_dns.Stop();
		}

		private void button7_Click(object sender, EventArgs e)
		{
			_server1.Stop();
		}

		private void button8_Click(object sender, EventArgs e)
		{
			_server2.Stop();
		}

		private void button9_Click(object sender, EventArgs e)
		{
			if (_dns != null)
			{
				StringBuilder sb = new StringBuilder();

				List<clsInfo> nodos = _dns.ObtenerLista();
				foreach (clsInfo nodo in nodos)
					sb.AppendLine(String.Format("Id:{0} {1}:{2}", nodo.ProcesoId, nodo.Ip, nodo.Puerto));

				MessageBox.Show(sb.ToString());
			}
		}


		public void IniciarNodo1()
		{
			_server1 = new BerkeleyNode(100000, 9001, _dnsIP, _dnsPort, new TimeSpan());
			_server1.Start();
		}

		public void IniciarNodo2()
		{
			_server2 = new BerkeleyNode(100000, 9002, _dnsIP, _dnsPort, new TimeSpan());
			_server2.Start();
		}



    }
}